package com.hongru.system.controller;

import com.hongru.cms.entity.CmsContent;
import com.hongru.cms.entity.CmsCourse;
import com.hongru.cms.entity.CmsVideo;
import com.hongru.constant.DictConstant;
import com.hongru.ebean.EbeanUtil;
import com.hongru.system.dto.ChartSearchParam;
import com.hongru.ums.entity.*;
import com.hongru.util.DateUtils;
import com.hongru.util.StringUtil;
import com.hongru.vo.Result;
import io.ebean.DB;
import io.ebean.Ebean;
import io.ebean.ExpressionList;
import io.ebean.SqlRow;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.util.DataUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description
 * @Copyright (c) 1998-2022 北京新鸿儒世纪网络技术有限公司 All Rights Reserved.
 * @Url https://www.xinhongru.com
 * @ClassName IndexController
 * @Author salter <salter@vip.163.com>
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2022/5/7 15:20
 */
@RestController
@RequestMapping("/sys/index")
@Slf4j
@ApiIgnore
public class IndexController {

    @GetMapping(value = "/getMiniAreaData")
    public Result getMiniAreaData() {
        Map retMap = new HashMap<>();
        //查询用户总数
        ExpressionList<UmsMember> userEl = EbeanUtil.initExpressionList(UmsMember.class).where();
        retMap.put("memberTotal", userEl.findCount());
        //查询当天新增用户数
        userEl.between("createTime", DateUtils.getDayBegin(), DateUtils.getDayEnd());
        retMap.put("currMemberTotal", userEl.findCount());
        //用户七日统计图
        List<SqlRow> memberAreaData = getCountSqlRow("ums_member", "create_time", "id", DateUtils.getCurrDayOfNumDay(-7), null, "count", null);
        retMap.put("memberAreaData", memberAreaData);

        //查询动态总数
        ExpressionList<UmsDynamic> dynamicEl = EbeanUtil.initExpressionList(UmsDynamic.class).where();
        retMap.put("dynamicTotal", dynamicEl.findCount());
        //查询当天动态数
        dynamicEl.between("createTime", DateUtils.getDayBegin(), DateUtils.getDayEnd());
        retMap.put("currDynamicTotal", dynamicEl.findCount());
        //动态七日统计图
        List<SqlRow> dynamicAreaData = getCountSqlRow("ums_dynamic", "create_time", "id", DateUtils.getCurrDayOfNumDay(-7), null, "count", null);
        retMap.put("dynamicAreaData", dynamicAreaData);

        //查询健康问答总数
        ExpressionList<UmsQa> qaEl = EbeanUtil.initExpressionList(UmsQa.class).where();
        retMap.put("qaTotal", qaEl.findCount());
        //查询当天问答数
        qaEl.between("createTime", DateUtils.getDayBegin(), DateUtils.getDayEnd());
        retMap.put("currQaTotal", qaEl.findCount());
        //问答七日统计图
        List<SqlRow> qaAreaData = getCountSqlRow("ums_qa", "create_time", "id", DateUtils.getCurrDayOfNumDay(-7), null, "count", null);
        retMap.put("qaAreaData", qaAreaData);

        //以完善信息用户数
        int memberCompleteTotal = EbeanUtil.initExpressionList(UmsMember.class).eq("isComplete", DictConstant.YN_1).findCount();
        //报告进行中用户数
        int memberMrStatus1Total = EbeanUtil.initExpressionList(UmsMember.class).eq("mrStatus", DictConstant.MR_STATUS_1).findCount();
        //报告完成用户数
        int memberMrStatus2Total = EbeanUtil.initExpressionList(UmsMember.class).eq("mrStatus", DictConstant.MR_STATUS_2).findCount();

        retMap.put("memberCompleteTotal", memberCompleteTotal);
        retMap.put("memberMrStatus1Total", memberMrStatus1Total);
        retMap.put("memberMrStatus2Total", memberMrStatus2Total);

        //文章数
        Integer contentTotal = EbeanUtil.initExpressionList(CmsContent.class).findCount();
        //视频数
        Integer videoTotal = EbeanUtil.initExpressionList(CmsVideo.class).findCount();
        //健康课堂数
        Integer courseTotal = EbeanUtil.initExpressionList(CmsCourse.class).findCount();
        retMap.put("contentTotal", contentTotal);
        retMap.put("videoTotal", videoTotal);
        retMap.put("courseTotal", courseTotal);

        //整体医学报告数
        int f112Count = EbeanUtil.initExpressionList(UmsMr.class).eq("categoryCode", "F112").findCount();
        //运动康复报告
        int f119Count = EbeanUtil.initExpressionList(UmsMr.class).eq("categoryCode", "F119").findCount();
        //营养饮食报告
        int f118Count = EbeanUtil.initExpressionList(UmsMr.class).eq("categoryCode", "F118").findCount();
        //中医体质报告
        int f113Count = EbeanUtil.initExpressionList(UmsMr.class).eq("categoryCode", "F113").findCount();
        //皮肤管理报告
        int f121Count = EbeanUtil.initExpressionList(UmsMr.class).eq("categoryCode", "F121").findCount();
        //体能健身报告
        int f120Count = EbeanUtil.initExpressionList(UmsMr.class).eq("categoryCode", "F120").findCount();
        retMap.put("f112Count", f112Count);
        retMap.put("f119Count", f119Count);
        retMap.put("f118Count", f118Count);
        retMap.put("f113Count", f113Count);
        retMap.put("f121Count", f121Count);
        retMap.put("f120Count", f120Count);

        //临床体检检测报告数
        int f111Count = EbeanUtil.initExpressionList(UmsPe.class).eq("categoryCode", "F111").findCount();
        //整体医学检测报告数
        int f110Count = EbeanUtil.initExpressionList(UmsPe.class).eq("categoryCode", "F110").findCount();
        //身体成分检测报告数
        int f19Count = EbeanUtil.initExpressionList(UmsPe.class).eq("categoryCode", "F19").findCount();
        retMap.put("f111Count", f111Count);
        retMap.put("f110Count", f110Count);
        retMap.put("f19Count", f19Count);


        return Result.OK(retMap);
    }

    public List<SqlRow> getCountSqlRow(String tableName, String dateColumnName, String countColumnName, Date beginDate, Date endDate, String fun, String where) {
        if (null == endDate) {
            endDate = new Date();
        }
        String userDataSql = "SELECT  IFNULL( " + fun + "(trbg." + countColumnName + "),0 )y," +
                "                        DATE_FORMAT(date, '%c.%e') x" +
                "                     FROM(" +
                "                         SELECT @cdate := DATE_FORMAT(date_add(@cdate, INTERVAL 1 day), \"%Y-%m-%d\") date" +
                "                         FROM(" +
                "                        SELECT @cdate := DATE_ADD('" + DateUtils.formatDate(beginDate, "yyyy-MM-dd") + "', INTERVAL -1 day)" +
                "                          FROM  temp  " +
                "                        LIMIT " + (DateUtils.getDiffDays(beginDate, endDate) + 1) + ") a) t_date" +
                "                          LEFT JOIN (SELECT * from " + tableName + (StringUtil.isEmpty(where) ? "" : " where " + where) + " )trbg  ON DATE_FORMAT(trbg." + dateColumnName + ", '%Y-%m-%d')= t_date.date " +
                "                          GROUP BY date";
        return DB.createSqlQuery(userDataSql).findList();
    }

    @PostMapping(value = "/getBarData")
    public Result getBarData(@RequestBody ChartSearchParam chartSearchParam) {
        Date beginDate = new Date();
        Date endDate = new Date();
        //本周
        if (chartSearchParam.getPeriod().equals(DictConstant.PERIOD_WEEK)) {
            beginDate = DateUtils.getBeginDayOfWeek();
        }
        //本月
        if (chartSearchParam.getPeriod().equals(DictConstant.PERIOD_MONTH)) {
            beginDate = DateUtils.getBeginDayOfMonth();
        }
        //区间查询
        if (StringUtil.isNotEmpty(chartSearchParam.getBeginDate())) {
            beginDate = DateUtils.str2Date(chartSearchParam.getBeginDate(), new SimpleDateFormat("yyyy-MM-dd"));
            endDate = DateUtils.str2Date(chartSearchParam.getEndDate(), new SimpleDateFormat("yyyy-MM-dd"));
        }
        List<SqlRow> sqlRowList = null;
        if ("ums_member".equals(chartSearchParam.getTableName())) {
            //查询用户增长情况
            sqlRowList = getCountSqlRow(chartSearchParam.getTableName(), "create_time", "id", beginDate, endDate, "count", null);
        }
        if ("ums_member_login_log".equals(chartSearchParam.getTableName())) {
            //查询用户活跃情况
            sqlRowList = getCountSqlRow(chartSearchParam.getTableName(), "create_time", "id", beginDate, endDate, "count", " 1=1 group by member_id");
        }
        return Result.OK(sqlRowList);
    }


}
